package com.ruoyi.law.annotation.handler;

import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.law.annotation.Statistics;
import com.ruoyi.law.domain.dto.LawNewsDTO;
import com.ruoyi.law.domain.entity.LawNews;
import com.ruoyi.law.service.ILawNewsService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 统计接口调用数量处理类
 *
 * @author lie
 * @date 2023/01/04
 */
@Component
@Aspect
public class StatisticsHandler {

    @Autowired
    private ILawNewsService newsService;

    private final ThreadPoolExecutor executor = ThreadUtil.newExecutor(3, 6);

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(statistics)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Statistics statistics, Object jsonResult) {
        executor.execute(() -> {
            R<?> r = (R<?>) jsonResult;
            LawNewsDTO news = (LawNewsDTO) r.getData();
            int num = news.getNum() == null ? 0 : news.getNum();
            LambdaUpdateWrapper<LawNews> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(LawNews::getId, news.getId());
            updateWrapper.set(LawNews::getNum, num + 1);
            newsService.update(updateWrapper);
        });
    }
}
